//系统配置对象
$.extend($.system.config, {
    //懒惰模式自动加载js,默认null,不加载
    /*
     * pageFolder:页面所在文件夹
     * scriptFolder:js所在文件夹
     * include:哪些路径需要自动加载js,可以是字符串,也可以是个数组
     */
    lazyLoad: {
        include: '/',
        pageFolder: '/page/',
        scriptFolder: '/script/'
    },
    //下载地址
    downloadPath: '',
    //记录点击左侧菜单的id
    nodeParentId: '',
    //jquery异步访问开始时执行的方法
    ajaxStart: function () {
        if (!($.easyui && $.easyui.loading())) {
            $.easyui.loading({
                msg: this.loadHit,
                topMost: true
            });
        }
    },
    //jquery异步访问完成时执行
    ajaxComplete: function (event, request, settings) {
        !($.easyui && $.easyui.loaded()) || $.easyui.loaded(true);
    },
    //jquery异步访问出错时执行，easyui extensions扩展已经拦截status<=500的错误
    ajaxError: function (XMLHttpRequest, textStatus, errorThrown) {
        //5011错误是异步登录验证不通过时返回的错误
        if (textStatus.status == 5011) {
            if (top.$.mainpage
                && top.$.mainpage.mainTabs
                && top.$.mainpage.mainTabs.target
                && top.$.mainpage.mainTabs.target.tabs('exists', 1)) {
                top.$.page.lockSystem(2);
            } else {
                $.messager.alert('超时提示', '登录超时，请重新登录系统！', function () {
                    top.location.href = $.util.getRootPath() + '/login.html';
                });
            }
        }
    }
});
$.page = {
    loginOut: function (type) {
        $.util.get($.util.getRootPath() + '/portal?logout', function (json) {
            if (json.success) {
                if (type == 1) {//锁定系统
                    showLoginDialog('系统锁定中...');
                } else {//退出系统
                    top.location.href = $.util.getRootPath() + '/login.html';
                }
            }
        });
    },
    lockSystem: function (type) {
        if (type == 2) {
            showLoginDialog('登录超时，请重新登录，登录之后刷新子页面！');
        } else {
            $.util.get($.util.getRootPath() + '/portal?logout', function (json) {
                if (json.success) {
                    if (type == 1) {//锁定系统
                        showLoginDialog('系统锁定中...');
                    } else {//退出系统
                        top.location.href = $.util.getRootPath() + '/login.html';
                    }
                }
            });
        }

        function showLoginDialog(title) {
            var dialog = $.easyui.showDialog({
                title: title,
                width: 330,
                height: 170,
                closable: false,
                href: $.util.getRootPath() + '/rsframe/page/index/login_dialog.html',
                topMost: true,
                enableCloseButton: false,
                saveButtonText: '登录',
                saveButtonIconCls: 'icon-hamburg-user',
                onSave: function () {
                    doLogin(dialog);
                },
                onLoad: function () {
                    var _username = $.cookie('l_username');
                    if (_username && _username.replace('null', '')) {
                        top.$('#userName').val(_username);
                    }
                    top.$('#userPassword').focus();
                    $(document).keydown(function (event) {
                        if (event.keyCode == 13 && top.$('#userName').val() && top.$('#userPassword').val()) {
                            doLogin(dialog);
                        }
                    });
                }
            });
        }

        function doLogin(dialog) {
            var userName = top.$('#userName').val();
            var password = top.$('#userPassword').val();
            if (userName && password) {
                $.page.doLogin(userName, password, function (res) {
                    if (res.statusCode != 200) {
                        $.easyui.loaded();
                        $.easyui.messager.show('提示消息', res.message, 'info');
                        return;
                    }
                    dialog.dialog('close');
                });
            }
        }
    },
    doLogin: function (username, password, callback) {
        var url = $.util.getRequestJson('/json/portal/getkey.json');
        $.get(url, function (json) {
            if (json.success) {
                $.easyui.loading();
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(json.data.secKey);
                var encryptPassword = encrypt.encrypt(password);
                url = $.util.getRequestJson('/json/portal/login.json');
                $.post(url, {username: username, password: encryptPassword}, function (res) {
                    if ($.util.isFunction(callback)) {
                        callback(res);
                    }
                });
            } else {
                $.easyui.messager.show('提示消息', json.message, 'info');
            }
        });
    },
    /**
     * type 1：导航菜单，2：工具栏按钮，3：操作按钮，4：自定义资源
     * state 1:close 0:open
     * getChild 1:获取子节点 0:不获取子节点
     */
    loadOperateData: function (state, type, getChild, callBack) {
        var url = $.util.getRootPath() + '/index/index_getNodesByPid.action?parentId=' + $.util.getRequest('path') + '&state=' + state + '&type=' + type + '&getChild=' + getChild;
        $.util.post(url, function (json) {
            switch (type) {
                case 2://toolbar按钮
                    handleToolbar();
                    break;
                case 3://普通按钮
                    handleOperate();
                    break;
                default:

                    break;
            }

            function handleOperate() {
                if ($.util.isFunction(callBack)) {
                    for (var i = 0; i < json.items.length; i++) {
                        var src = json.items[i].src;
                        if (src && src.indexOf("function/") >= 0) {
                            json.items[i].handler = src.substring("function/".length, src.indexOf("?")) + '("{param}");';
                        }
                    }
                    callBack(json.items);
                }
            }

            function handleToolbar() {
                var items = [];
                var data = json.items;
                for (var i = 0, j = 0; i < data.length; i++) {
                    var src = data[i].src;
                    if (src && src.indexOf("function/") >= 0) {
                        var handlerFun = 'function(){' + src.substring("function/".length, src.indexOf("?")) + '();}';
                        data[i].handler = eval("0,(" + handlerFun + ")");
                    }
                    if (data[i] != '-') {
                        items[j] = data[i];
                        j++;
                        if ((i + 1) != data.length) {
                            items[j] = "-";
                            j++;
                        }
                    } else {
                        items[j] = data[i];
                    }
                }
                if ($.util.isFunction(callBack)) {
                    callBack(items);
                }
            }

        });
    }
};
$(function () {
    //前后端分离需要异步请求自身携带cookies
    if ($.system.config.enableWeb) {
        // $.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true}});
        $.ajaxSetup({xhrFields: {withCredentials: true}});
    }
    //暂时将请求封装到此处
    $.util.getRequestJson = function (url) {
        //如果是web接口请求,更换为web接口地址
        var rootPath = $.util.getRootPath();
        if ($.system.config.enableWeb) {
            var jsonDir = "/json/";
            var jsonIndex = url.indexOf(jsonDir);
            if (jsonIndex >= 0) {
                url = url.substr(jsonIndex + jsonDir.length - 1, url.length);
            }
            url = url.replaceAll(".json", "#dot#json");
            url = url.replaceAll(".", "/").replaceAll("#dot#", ".");
            if ($.system.config.interfacePath) {
                rootPath = $.system.config.interfacePath;
            }
        } else {
            //增加本地json参数
            if (url.indexOf("?") > 0) {
                url = url + "&locationJson=1";
            } else {
                url = url + "?locationJson=1";
            }
        }
        return rootPath + url;
    };
    //jquery异步访问开始时执行
    $(document).ajaxSend(function (evt, request, settings) {
    });
    //jquery异步访问开始时执行
    $(document).ajaxStart(function (evt, request, settings) {
        $.system.config.ajaxStart && $.system.config.ajaxStart();
    });
    //jquery异步访问完成时执行
    $(document).ajaxComplete(function (event, request, settings) {
        $.system.config.ajaxComplete && $.system.config.ajaxComplete(event, request, settings);
    });
    //jquery异步访问出错时执行
    $(document).ajaxError(function (XMLHttpRequest, textStatus, errorThrown) {
        $.system.config.ajaxError && $.system.config.ajaxError(XMLHttpRequest, textStatus, errorThrown);
    });
    var lazyLoad = $.system.config.lazyLoad ? $.system.config.lazyLoad : {};
    //处理panel使用href加载内容时的动态js加载
    $.fn.panel.defaults.globalHandler = function (opts) {
        $.util.exec(function () {
            var url = opts.href, pageFolder = lazyLoad.pageFolder, scriptFolder = lazyLoad.scriptFolder;
            if (lazyLoad && $.string.contains(url, lazyLoad.include)) {
                //增加所有的请求参数
                var localUrl = parent.location.href;
                intPos = localUrl.indexOf("#&");
                localUrl = intPos > 0 ? localUrl.substr(0, intPos) : localUrl;
                var intPos = url.indexOf("?");
                var param = intPos > 0 ? url.substr(intPos + 1) : '';
                var params = $.unique(param.split('&'));
                for (var i = 0; i < params.length; i++) {
                    if (i == 0) {
                        localUrl += '#&' + params[i];
                    } else {
                        localUrl += '&' + params[i];
                    }
                }
                parent.location.href = localUrl;
                url = pageFolder && scriptFolder ? url.replace(pageFolder, scriptFolder) : url;
                url = intPos > 0 ? url.substr(0, intPos) : url;
                if (/\/.*\..*$/.test(url)) {//只有请求页面的自动加载js
                    parent.$.util.loadJs(url.replace(/.[^.]+$/, ".js?_=" + (new Date()).valueOf()));
                }
            }
        }, 50);
    };
    $.util.exec(function () {
        document.title = $.system.config.title + $.system.config.version;
        var cookieTheme = $.cookie("easyuiTheme"), theme = cookieTheme ? cookieTheme : $.util.$.easyui.theme();
        $.easyui.theme(theme);
        //曹传喜于 2014/8/26增加目的自动根据页面加载指定位置js -- begin
        var url = $.util.currentUri, pageFolder = lazyLoad.pageFolder, scriptFolder = lazyLoad.scriptFolder;
        if (lazyLoad && $.string.contains(url, lazyLoad.include)) {
            var currentPath = $.util.currentPath;
            if (currentPath !== $.util.getRootPath()) {
                url = pageFolder && scriptFolder ? url.replace(pageFolder, scriptFolder) : url;
                var intPos = url.indexOf("?");
                url = intPos > 0 ? url.substr(0, intPos) : url;
                if (/\/.*\..*$/.test(url)) {//只有请求页面的自动加载js
                    $.util.loadJs(url.replace(/.[^.]+$/, ".js?_=" + (new Date()).valueOf()));
                }
            }
        }
        //曹传喜于 2014/8/26增加 -- end
    });
    /**
     * 临时form处理，后期集成到jeasyui.extensions.form.js中
     */
    function triangleForm(){
        var easyuiForm = $('.easyui-form');
        if (easyuiForm.length > 0) {
            easyuiForm.each(function () {
                var form = $(this);
                if (!form.attr('init-true')) {
                    form.attr('init-true', 'true');
                    //初始化选项箭头
                    var triangle = ('<div class="triangle down-triangle"></div>');
                    var title = form.find('thead');
                    console.info(title);
                    title.find('th').append(triangle);
                    $(title).on('click', function () {
                        var down = $(this).find('.triangle');
                        if (down.hasClass('down-triangle')) {
                            down.removeClass('down-triangle');
                            down.addClass('up-triangle');
                            $(this).parent().find('tbody').hide();
                        } else {
                            down.removeClass('up-triangle');
                            down.addClass('down-triangle');
                            $(this).parent().find('tbody').show();
                        }
                    });
                }
            });
        }
    }
    $('body').on('DOMNodeInserted', function () {
        triangleForm();
    });

    triangleForm();

    function extendAjax() {
        // 首先备份下jquery的ajax方法
        var _ajax = $.ajax;

        // 重写jquery的ajax方法
        $.ajax = function (options) {
            // 备份opt中error和success方法
            var callback = {
                "beforeSend": function (XHR) {
                },
                "complete": function (XHR, TS) {
                },
                "error": function (XMLHttpRequest, textStatus, errorThrown) {
                },
                "success": function (data, textStatus) {
                }
            };

            // 判断参数中是否有beforeSend回调函数
            if (options.beforeSend) {
                callback.beforeSend = options.beforeSend;
            }

            // 判断参数中是否有complete回调函数
            if (options.complete) {
                callback.complete = options.complete;
            }

            // 判断参数中是否有error回调函数
            if (options.error) {
                callback.error = options.error;
            }

            // 判断参数中是否有success回调函数
            if (options.success) {
                callback.success = options.success;
            }

            // 扩展增强处理
            var _opt = $.extend(options, {
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // 错误方法增强处理
                    callback.error(XMLHttpRequest, textStatus, errorThrown);
                },
                success: function (data, textStatus) {
                    // 成功回调方法增强处理
                    try {
                        callback.success($.util.parseJSON(data), textStatus);
                    } catch (e) {
                        callback.success(data, textStatus);
                    }
                },
                beforeSend: function (XHR) {
                    // 提交前回调方法
                    callback.beforeSend(XHR);
                },
                complete: function (XHR, TS) {
                    // 请求完成后回调函数 (请求成功或失败之后均调用)。
                    callback.complete(XHR, TS);
                },
                cache: false
            });

            // 返回重写的ajax
            return _ajax(_opt);
        };
    }

    extendAjax();
    //初始化工具类的rootPath解决本地开发路径异常问题
    if ($ && $.util && !$.util.rootPath) {
        $.util.rootPath = pageRootPath;
    }
});
